package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.cache.CategoryCache;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.client.search.SearchClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.*;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.QuestionAdminPageQuery;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.vo.QuestionAdminVO;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>
 *
 * @author zhongweiwei
 * @since 2023-05-29
 */
@RequiredArgsConstructor
@Service
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {

    private final UserClient userClient;
    private final InteractionReplyMapper replyMapper;
    private final SearchClient searchClient;
    private final CourseClient courseClient;
    private final CatalogueClient catalogueClient;
    private final CategoryCache categoryCache;

    /**
     * 新增问题接口
     *
     * @param questionDTO
     */
    @Override
    public void addInteractionQuestion(QuestionFormDTO questionDTO) {
        //1-获取用户id
        Long userId = UserContext.getUser();
        if (userId == null) {
            return;
        }
        //2-属性copy，和赋值
        InteractionQuestion question = BeanUtils.copyBean(questionDTO, InteractionQuestion.class);
        question.setUserId(userId);
        this.save(question);
    }

    /**
     * 根据id查询互动问题
     *
     * @param id
     * @return
     */
    @Override
    public QuestionVO queryQuestionById(Long id) {
        //1-根据id获取问题信息
        InteractionQuestion question = getById(id);
        if (question == null || question.getAnonymity()) {
            return null;
        }
        UserDTO user = null;
        if (!question.getAnonymity()) {
            user = userClient.queryUserById(question.getUserId());
        }
        QuestionVO questionVO = BeanUtils.copyBean(question, QuestionVO.class);
        if (user != null) {
            questionVO.setUserName(user.getName());
            questionVO.setUserIcon(user.getIcon());

        }
        return questionVO;
    }

    /**
     * 分页查询互动问题
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<QuestionVO> queryQuestionPage(QuestionPageQuery query) {
        //1-获取章，节的id并且不能为null
        Long courseId = query.getCourseId();
        Long sectionId = query.getSectionId();
        if (courseId == null && sectionId == null) {
            //如果为空则返还空数据
            return PageDTO.empty(0L, 0L);
        }
        //构建查询对象
        Page<InteractionQuestion> page = lambdaQuery()
                .select(InteractionQuestion.class, info -> !info.getProperty().equals("description"))
                .eq(courseId!=null , InteractionQuestion::getCourseId, courseId)
                .eq(sectionId!=null, InteractionQuestion::getSectionId, sectionId)
                .eq(query.getOnlyMine(), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(InteractionQuestion::getHidden, false)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = page.getRecords();
        //判断查询的结果集是否为空
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        //不为空则准备vo数据
        Set<Long> userIds = new HashSet<>();
        Set<Long> answerIds = new HashSet<>();
        for (InteractionQuestion record : records) {
            //只收集不选择匿名提问的的用户
            if (!record.getAnonymity()) {
                userIds.add(record.getUserId());
            }
            answerIds.add(record.getLatestAnswerId());
        }
        //根据最近回答id查询回答
        answerIds.remove(null);
        Map<Long, InteractionReply> replyMap = new HashMap<>(answerIds.size());
        if (BeanUtils.isNotEmpty(answerIds)) {
            List<InteractionReply> replies = replyMapper.selectBatchIds(answerIds);
            for (InteractionReply reply : replies) {
                replyMap.put(reply.getId(), reply);
                if (!reply.getAnonymity()) {
                    userIds.add(reply.getUserId());
                }
            }
        }
        userIds.remove(null);
        Map<Long, UserDTO> userMap = new HashMap<>(userIds.size());
        if (CollUtils.isNotEmpty(userIds)) {
            List<UserDTO> users = userClient.queryUserByIds(userIds);
            userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
        }
        //封装Vo
        List<QuestionVO> questionVOList = new ArrayList<>(records.size());
        for (InteractionQuestion record : records) {
            QuestionVO vo = BeanUtils.copyBean(record, QuestionVO.class);
            questionVOList.add(vo);
            if (!record.getAnonymity()) {
                UserDTO userDTO = userMap.get(record.getUserId());
                if (userDTO != null) {
                    vo.setUserName(userDTO.getUsername());
                    vo.setUserIcon(userDTO.getIcon());
                }
            }
            InteractionReply reply = replyMap.get(record.getLatestAnswerId());
            if (reply != null) {
                vo.setLatestReplyContent(reply.getContent());
                if (!reply.getAnonymity()) {
                    UserDTO user = userMap.get(reply.getUserId());
                    vo.setLatestReplyUser(user.getName());
                }
            }


        }

        return PageDTO.of(page, questionVOList);
    }

    /**
     * 删除问题
     *
     * @param id
     */
    @Override
    public void deleteQuestion(Long id) {
        //获取问题
        InteractionQuestion question = this.getById(id);
        if (Objects.isNull(question)) {
            throw new RuntimeException("删除问题不存在");
        }
        Long userId = UserContext.getUser();
        if (!question.getUserId().equals(userId)) {
            throw new RuntimeException("只能删除相同用户的问题");
        }
        removeById(id);
        // 删除关联的回答
        replyMapper.delete(
                new QueryWrapper<InteractionReply>().lambda().eq(InteractionReply::getQuestionId, id)
        );

    }


    /**
     * 根据问题id修改went
     *
     * @param id
     */
    @Override
    public void updateQuestion(Long id, QuestionFormDTO questionDTO) {
        InteractionQuestion question = this.getById(id);
        if (Objects.isNull(question)) {
            throw new RuntimeException("问题不存在");
        }
        if (!question.getUserId().equals(UserContext.getUser())) {
            throw new RuntimeException("只能修改相同用户的问题");
        }
        InteractionQuestion question1 = BeanUtils.copyProperties(questionDTO, InteractionQuestion.class);
        question1.setId(id);
        updateById(question1);


    }

    /**
     * 管理端-分页查询问题
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<QuestionAdminVO> queryQuestionPageAdmin(QuestionAdminPageQuery query) {
        // 1.处理课程名称，得到课程id
        List<Long> courseIds = null;
        if (StringUtils.isNotBlank(query.getCourseName())) {
            courseIds = searchClient.queryCoursesIdByName(query.getCourseName());
            if (CollUtils.isEmpty(courseIds)) {
                return PageDTO.empty(0L, 0L);
            }
        }
        // 2.分页查询
        Integer status = query.getStatus();
        LocalDateTime begin = query.getBeginTime();
        LocalDateTime end = query.getEndTime();
        Page<InteractionQuestion> page = lambdaQuery()
                .in(courseIds != null, InteractionQuestion::getCourseId, courseIds)
                .eq(status != null, InteractionQuestion::getStatus, status)
                .gt(begin != null, InteractionQuestion::getCreateTime, begin)
                .lt(end != null, InteractionQuestion::getCreateTime, end)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }

        // 3.准备VO需要的数据：用户数据、课程数据、章节数据
        Set<Long> userIds = new HashSet<>();
        Set<Long> cIds = new HashSet<>();
        Set<Long> cataIds = new HashSet<>();
        // 3.1.获取各种数据的id集合
        for (InteractionQuestion q : records) {
            userIds.add(q.getUserId());
            cIds.add(q.getCourseId());
            cataIds.add(q.getChapterId());
            cataIds.add(q.getSectionId());
        }
        // 3.2.根据id查询用户
        List<UserDTO> users = userClient.queryUserByIds(userIds);
        Map<Long, UserDTO> userMap = new HashMap<>(users.size());
        if (CollUtils.isNotEmpty(users)) {
            userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
        }

        // 3.3.根据id查询课程
        List<CourseSimpleInfoDTO> cInfos = courseClient.getSimpleInfoList(cIds);
        Map<Long, CourseSimpleInfoDTO> cInfoMap = new HashMap<>(cInfos.size());
        if (CollUtils.isNotEmpty(cInfos)) {
            cInfoMap = cInfos.stream().collect(Collectors.toMap(CourseSimpleInfoDTO::getId,Function.identity()));
        }

        // 3.4.根据id查询章节
        List<CataSimpleInfoDTO> catas = catalogueClient.batchQueryCatalogue(cataIds);
        Map<Long, String> cataMap = new HashMap<>(catas.size());
        if (CollUtils.isNotEmpty(catas)) {
            cataMap = catas.stream()
                    .collect(Collectors.toMap(CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName));
        }


        // 4.封装VO
        List<QuestionAdminVO> voList = new ArrayList<>(records.size());
        for (InteractionQuestion q : records) {
            // 4.1.将PO转VO，属性拷贝
            QuestionAdminVO vo = BeanUtils.copyBean(q, QuestionAdminVO.class);
            voList.add(vo);
            // 4.2.用户信息
            UserDTO user = userMap.get(q.getUserId());
            if (user != null) {
                vo.setUserName(user.getName());
            }
            // 4.3.课程信息以及分类信息
            CourseSimpleInfoDTO cInfo = cInfoMap.get(q.getCourseId());
            if (cInfo != null) {
                vo.setCourseName(cInfo.getName());
                vo.setCategoryName(categoryCache.getCategoryNames(cInfo.getCategoryIds()));
            }
            // 4.4.章节信息
            vo.setChapterName(cataMap.getOrDefault(q.getChapterId(), ""));
            vo.setSectionName(cataMap.getOrDefault(q.getSectionId(), ""));
        }
        return PageDTO.of(page, voList);
    }

    /**
     * 管理端根据id查询互动问题
     *
     * @param id
     * @return
     */
    @Override
    public QuestionAdminVO queryQuestionByIdAdmin(Long id) {
        InteractionQuestion question = getById(id);
        if (BeanUtils.isEmpty(question)) {
            throw new BadRequestException("该问题不存在");
        }
        QuestionAdminVO vo = BeanUtils.copyBean(question, QuestionAdminVO.class);
        //查询提问者信息
        UserDTO user = userClient.queryUserById(question.getUserId());
        if (user != null) {
            vo.setUserName(user.getName());
            vo.setUserIcon(user.getIcon());

        }
        //查询课程信息
        CourseFullInfoDTO courseInfoById = courseClient.getCourseInfoById(question.getCourseId(), false, false);
        if (!Objects.isNull(courseInfoById)) {
            vo.setCourseName(courseInfoById.getName());
        }
        //查询章节信息
        List<CataSimpleInfoDTO> simpleInfoDTOS = catalogueClient.batchQueryCatalogue(
                List.of(question.getChapterId(), question.getSectionId())
        );
        Map<Long, String> cataMap = new HashMap<>(simpleInfoDTOS.size());
        if (CollUtils.isNotEmpty(simpleInfoDTOS)) {
            cataMap = simpleInfoDTOS.stream()
                    .collect(Collectors.toMap(CataSimpleInfoDTO::getId, CataSimpleInfoDTO::getName));
        }
        vo.setChapterName(cataMap.getOrDefault(question.getChapterId(), ""));
        vo.setSectionName(cataMap.getOrDefault(question.getSectionId(), ""));

        //查询分类信息
        vo.setCategoryName(categoryCache.getCategoryNames(courseInfoById.getCategoryIds()));
        //查询老师信息
        List<Long> teacherIds = courseInfoById.getTeacherIds();
        List<UserDTO> teachers = userClient.queryUserByIds(teacherIds);
        if (!teachers.isEmpty()) {
            vo.setTeacherName(teachers.stream()
                    .map(UserDTO::getName).collect(Collectors.joining("/")));
        }


        return vo;
    }

    /**
     * 隐藏或显示问题
     *
     * @param id
     * @param hidden
     */
    @Override
    public void hiddenQuestion(Long id, Boolean hidden) {
        InteractionQuestion question = getById(id);
        if (Objects.isNull(question)) {
            throw new BadRequestException("该问题不存在");
        }
        //更新问题状态
        question.setHidden(hidden);
        question.setId(id);
        updateById(question);
    }
}
